package com.ljx.itbbs.server.article.dao;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.itbbs.common.domain.enums.CommonStatusEnum;
import com.ljx.itbbs.common.domain.vo.resp.CursorResp;
import com.ljx.itbbs.server.article.domain.entity.CommentEntity;
import com.ljx.itbbs.server.article.domain.entity.CommentReplyEntity;
import com.ljx.itbbs.server.article.domain.vo.req.ArticleCommentReq;
import com.ljx.itbbs.server.article.mapper.CommentReplyMapper;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;

@Service
public class CommentReplyDao extends ServiceImpl<CommentReplyMapper, CommentReplyEntity> {

    public CursorResp<CommentReplyEntity> getCommentReplyList(ArticleCommentReq req) {
        LambdaQueryWrapper<CommentReplyEntity> wrapper = new LambdaQueryWrapper<>();
        // 游标条件
        wrapper.eq(CommentReplyEntity::getStatus, CommonStatusEnum.NORMAL.getStatus());
        wrapper.eq(CommentReplyEntity::getCommentId, req.getCommentId());
        // 游标字段
        if (Objects.nonNull(req.getCursor())){
            wrapper.gt(CommentReplyEntity::getId, req.getCursor());
        }
        // 游标方向
        // wrapper.orderByDesc(CommentReplyEntity::getId);
        Page<CommentReplyEntity> page = this.baseMapper.selectPage(req.plusPage(), wrapper);
        // 计算游标位置
        String cursor = Optional.ofNullable(CollectionUtil.getLast(page.getRecords()))
                .map(CommentReplyEntity::getId)
                .map(String::valueOf)
                .orElse(null);
        return CursorResp.<CommentReplyEntity>builder()
                .list(page.getRecords())
                .cursor(cursor)
                .isLast(page.getRecords().size() != req.getPageSize())
                .build();
    }

    public void likeCommentReply(Long id) {
        lambdaUpdate().setSql("like_num = like_num + 1")
                .eq(CommentReplyEntity::getId, id)
                .update();
    }

    public void reduceCommentReplyLikeNum(Long id) {
        lambdaUpdate().setSql("like_num = like_num - 1")
                .eq(CommentReplyEntity::getId, id)
                .update();
    }
}
